﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Teal.Compiler {

    /// <summary>
    /// 表示一个成员（如方法、字段、类、模块等）定义。
    /// </summary>
    public abstract partial class MemberDefinition {

    }

    /// <summary>
    /// 表示一个可以保存子成员的容器成员定义。
    /// </summary>
    public abstract partial class MemberContainerDefinition {

        public MemberDefinition getMember(int index) {
            for (var m = members; m != null; m = m.next) {
                if (index-- <= 0) {
                    return m;
                }
            }
            throw new ArgumentOutOfRangeException("index");
        }

        public void addMember(MemberDefinition member) {
            var m = members;
            while (m.next != null) {
                m = m.next;
            }
            m.next = member;
        }

        public void removeMember(MemberDefinition member) {
            if (members == member) {
                members = members.next;
                return;
            }
            for (var m = members; m != null; m = m.next) {
                if (m.next == member) {
                    m.next = m.next.next;
                    return;
                }
            }
        }

    }

    /// <summary>
    /// 表示一个编译器。用于存储相关的配置数据以及提供公共的编译辅助函数。
    /// </summary>
    public static partial class Compiler {

        /// <summary>
        /// 使用当前编译器编译指定的源码。
        /// </summary>
        /// <param name="sourceCode">要编译的源码。</param>
        /// <param name="savePath">生成文件的位置。</param>
        public static void compile(string sourceCode, string savePath) {

            Compiler.options.outputPath = savePath;

            var parser = new Parser();
            currentPackage.mainModule.members = parser.parseString(sourceCode);

            currentPackage.resolve();
            if (Compiler.errorCount != 0) {
                return;
            }

            currentPackage.emit();

            currentPackage.save();

        }

    }

}
